package cn.jsprun.struts.action;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.jsprun.domain.Members;
import cn.jsprun.service.system.DataBaseService;
import cn.jsprun.utils.BeanFactory;
import cn.jsprun.utils.Common;
import cn.jsprun.vo.system.AdminnotesVO;
import cn.jsprun.vo.system.TableStatusVO;

public class HomeManageAction extends DispatchAction {
	private DataBaseService dataBaseService = (DataBaseService) BeanFactory.getBean("dataBaseService");
	public ActionForward getData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		List<Map<String,String>> adminsessions=dataBaseService.executeQuery("SELECT a.*, m.username, m.adminid, m.regip FROM jrun_adminsessions a LEFT JOIN jrun_members m USING(uid) ORDER BY a.errorcount");
		request.setAttribute("adminsessions", adminsessions);
		HttpSession session = request.getSession();
		Members members = (Members)session.getAttribute("members");
		byte adminid = (Byte)session.getAttribute("jsprun_adminid");
		if(adminid==1){
			request.setAttribute("forumselect", Common.forumselect(false, false,members!=null?members.getGroupid():7,members!=null?members.getExtgroupids():"",null,false));
			List<Map<String,String>> usergroups = dataBaseService.executeQuery("select groupid,grouptitle from jrun_usergroups");
			request.setAttribute("usergroupslist", usergroups);
		}
		String access = "";
		switch(adminid) {
		case 1: access = "4,5,6,7"; break;
		case 2: access = "2,3,6,7"; break;
		default: access = "1,3,5,7"; break;
		}
		List<Map<String,String>> adminnoteslist = dataBaseService.executeQuery("SELECT * FROM jrun_adminnotes WHERE access IN ( "+access+" ) ORDER BY dateline DESC");
		if(adminnoteslist!=null && adminnoteslist.size()>0){
			int timestamp = (Integer)(request.getAttribute("timestamp"));
			List<AdminnotesVO> adminnotelist = new ArrayList<AdminnotesVO>();
			for(int i=0;i<adminnoteslist.size();i++){
				Map<String,String> adminnotes = adminnoteslist.get(i);
				if(convertInt(adminnotes.get("expiration"))<timestamp){
					dataBaseService.runQuery("delete from jrun_adminnotes WHERE id='"+adminnotes.get("id")+"'");
				}else{
				AdminnotesVO notesvo = new AdminnotesVO();
				notesvo.setContext(adminnotes.get("message"));
				notesvo.setDateline(adminnotes.get("dateline"));
				notesvo.setExpiration(adminnotes.get("expiration"));
				notesvo.setUsername(adminnotes.get("admin"));
				String []accessShow = countshow(adminnotes.get("access"));
				notesvo.setIsadmin(accessShow[2]);
				notesvo.setIschaoban(accessShow[1]);
				notesvo.setIsbanzhu(accessShow[0]);
				notesvo.setId(adminnotes.get("id"));
				adminnotelist.add(notesvo);
				}
			}
			request.setAttribute("adminnotelist", adminnotelist);
		}
		request.setAttribute("times", Common.addTime(Calendar.MONTH,1).getTime()/1000);
		if(adminid==1){
				int maxupload = (int) (Runtime.getRuntime().maxMemory()/1024/1024/4);
				request.setAttribute("maxupload", maxupload);
			List<Map<String,String>> version = dataBaseService.executeQuery("select VERSION() as virsion;", new String[]{"virsion"});
			request.setAttribute("mysqlvirson", version.get(0).get("virsion"));
			String sysType = System.getProperty("os.name"); 
			request.setAttribute("sysType", sysType);
			String javaversion = System.getProperty("java.version");   
			request.setAttribute("jkdversion", javaversion);
			List<TableStatusVO> tableStatusVOs = dataBaseService.findTableStatus("SHOW TABLE STATUS LIKE 'jrun_%';");
			long totalsize = 0L;
			for (TableStatusVO statusVO : tableStatusVOs) {
					totalsize += statusVO.getData_length()	+ statusVO.getIndex_length();
			}
			request.setAttribute("totalsize", totalsize);
			String attachsize = request.getParameter("attasize");
			if(attachsize!=null){
				List<Map<String,String>> attasize = dataBaseService.executeQuery("SELECT SUM(filesize) as size FROM jrun_attachments");
				if(attasize!=null && attasize.size()>0){
					request.setAttribute("attasize", Common.toDigit(attasize.get(0).get("size"),10000000000000L,0L).longValue());
				}else{
					request.setAttribute("attasize", 0);
				}
			}
		}
		return mapping.findForward("home");
	}
	public ActionForward home(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		Members members = (Members)session.getAttribute("members");
		String delete[] = request.getParameterValues("delete[]");
		if(delete!=null){
			String deleteid = "0";
			for(int i=0;i<delete.length;i++){
				deleteid = deleteid + "," + delete[i];
			}
			dataBaseService.runQuery("delete from jrun_adminnotes where id in ( "+deleteid+" )");
		}
		String newmessage = request.getParameter("newmessage");
		if(newmessage!=null && !newmessage.equals("")){
			String newaccess1 = request.getParameter("newaccess[1]");
			String newaccess2 = request.getParameter("newaccess[2]");
			String newaccess3 = request.getParameter("newaccess[3]");
			newaccess1 = newaccess1==null?"0":newaccess1;
			newaccess2 = newaccess2==null?"0":newaccess2;
			newaccess3 = newaccess3==null?"0":newaccess3;
			short groupid = members.getGroupid();
			if(groupid==1){
				newaccess1 = "1";
			}else if(groupid==2){
				newaccess2 = "1";
			}else{
				newaccess3 = "1";
			}
			String newexpiration = request.getParameter("newexpiration");
			String times = "";
			SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date date = sm.parse(newexpiration);
				times = date.getTime()+"";
				times = times.substring(0,10);
			} catch (ParseException e) {
			}
			int access = countCustomreverse(new String[]{newaccess1,newaccess2,newaccess3});
			if(!times.equals("newmessage")){
				int timestamp = (Integer)(request.getAttribute("timestamp"));
				String sql = "INSERT INTO jrun_adminnotes (admin, access, adminid, dateline, expiration, message)VALUES ('"+members.getUsername()+"', '"+access+"', '"+members.getAdminid()+"', '"+timestamp+"', '"+times+"', '"+newmessage+"')";
				dataBaseService.runQuery(sql);
			}
		}
		try {
			String attasize = request.getParameter("attasize");
			if(attasize!=null){
				response.getWriter().write("<script type='text/javascript'>parent.menu.location='admincp.jsp?action=menu'; parent.main.location='admincp.jsp?action=home&attasize=1';</script>");
			}else{
				response.getWriter().write("<script type='text/javascript'>parent.menu.location='admincp.jsp?action=menu'; parent.main.location='admincp.jsp?action=home';</script>");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	private int convertInt(String str){
		int count = 0;
		try{
			count = Integer.valueOf(str);
		}catch(Exception e){
		}
		return count;
	}
	private String[] countshow(String setting) {
		int setvalue = Integer.valueOf(setting);
		String customs = setvalue % 2 + ",";
		int aa = setvalue / 2;
		customs += aa % 2 + ",";
		aa = aa / 2;
		customs += aa % 2;
		String cus[] = customs.split(",");
		return cus;
	}
	private int countCustomreverse(String[] cust) {
		int result = 0;
		result += convertInt(cust[0])*2*2;
		result += convertInt(cust[1]) * 2;
		result += convertInt(cust[2]);
		return result;
	}
}